import os, sys, urllib2,urlparse,re
USERAGENT='Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.8.1.11) Gecko/20071201 Firefox/2.0.0.11 (Swiftfox)'
#tag='lucky_star'
tag=sys.argv[1]
url='http://konachan.com/post?tags=%s' %tag
urlsrc=urllib2.urlopen(url).read()

def maxpage(url):
    maxpage=re.findall('<a href=".*?">(\d{1,2})</a>', urlsrc)
    maxpage=int(maxpage[len(maxpage)-1]) 
    print maxpage
    return maxpage

def get_urlimg(url,maxpage):
    urlimg=[]
    for i in range(1,maxpage+1):
        url='http://konachan.com/post?page=%s&tags=%s' %(i,tag)
        urlsrc=urllib2.urlopen(url).read()
        urlimg_s=re.findall('<a class=".*?" href="(http://konachan.com/data/.*?)"><span>(\d{1,} x \d{1,})</span></a></li>', urlsrc,)
        for f in range(len(urlimg_s)):
            urlimg.append(urlimg_s[f])
    
    return urlimg

def pic(urlimg):
    print len(urlimg)
    n=1
    for i in urlimg:
        urlimg=i
        name = urlimg[0].split('.')
        name = '%s-%s_[%s].%s' %(n,re.sub('/','_',tag),urlimg[1],name[2])
        n=n+1
        savepic(urlimg[0], name)
def savepic(urlimg,name):   
    try:
        img_r=urllib2.Request(urlimg)
        img_r.add_header('User-Agent', USERAGENT)
        img_r.add_header('Referer',url)
        img_r = urllib2.urlopen(img_r)
        
        img_w = open(name, 'w')
        img_w.write(img_r.read())
        img_w.close()
    except urllib2.HTTPError, msg:
        print "%s" % (msg)

    
def main(url):
    urlimg=get_urlimg(url, maxpage(url))
    print len(urlimg)
    pic(urlimg)

main(url)
#savepic('http://konachan.com/data/57c9d65b69e6ad2acbb64c9b6be9a7f0.jpg', 'lala')